import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../common/models/server_model.dart';
import '../../../../common/services/server_service.dart';

/// 服务器表单（支持添加和编辑）
class ServerForm extends StatefulWidget {
  final ServerModel? server; // 如果为 null 则是添加模式，否则是编辑模式
  final Future<void> Function({
    required String name,
    required String host,
    required int port,
    required String username,
    String? password,
    String? privateKey,
    String? groupId,
  }) onSubmit;

  const ServerForm({
    super.key,
    this.server,
    required this.onSubmit,
  });

  @override
  State<ServerForm> createState() => _ServerFormState();
}

class _ServerFormState extends State<ServerForm> {
  final _formKey = GlobalKey<FormState>();
  final ServerService _serverService = Get.find<ServerService>();
  
  late final TextEditingController _nameController;
  late final TextEditingController _hostController;
  late final TextEditingController _portController;
  late final TextEditingController _usernameController;
  late final TextEditingController _passwordController;
  
  String? _selectedGroupId; // 选中的分组 ID
  List<ServerGroup> _groups = [];

  bool get isEditMode => widget.server != null;

  @override
  void initState() {
    super.initState();
    // 加载分组列表
    _groups = _serverService.getAllGroups();
    
    // 初始化控制器，如果是编辑模式则填充现有数据
    _nameController = TextEditingController(text: widget.server?.name ?? '');
    _hostController = TextEditingController(text: widget.server?.host ?? '');
    _portController = TextEditingController(text: widget.server?.port.toString() ?? '22');
    _usernameController = TextEditingController(text: widget.server?.username ?? 'root');
    _passwordController = TextEditingController(text: widget.server?.password ?? '');
    _selectedGroupId = widget.server?.groupId;
  }

  @override
  void dispose() {
    _nameController.dispose();
    _hostController.dispose();
    _portController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        padding: EdgeInsets.only(
          left: 20,
          right: 20,
          top: 20,
          bottom: MediaQuery.of(context).viewInsets.bottom + 20,
        ),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              Row(
                children: [
                  Text(
                    isEditMode ? '编辑服务器' : '添加服务器',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    onPressed: () => Get.back(),
                    icon: const Icon(Icons.close),
                  ),
                ],
              ),
              const SizedBox(height: 20),

              // 名称
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '服务器名称',
                  hintText: '例如：我的服务器',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.label),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入服务器名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 分组选择
              DropdownButtonFormField<String>(
                value: _selectedGroupId,
                decoration: const InputDecoration(
                  labelText: '所属分组',
                  hintText: '选择分组（可选）',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.folder_outlined),
                ),
                items: [
                  const DropdownMenuItem(
                    value: null,
                    child: Text('默认分组'),
                  ),
                  ..._groups.map((group) {
                    return DropdownMenuItem(
                      value: group.id,
                      child: Text(group.name),
                    );
                  }),
                ],
                onChanged: (value) {
                  setState(() {
                    _selectedGroupId = value;
                  });
                },
              ),
              const SizedBox(height: 16),

              // 地址
              TextFormField(
                controller: _hostController,
                decoration: const InputDecoration(
                  labelText: 'IP 地址',
                  hintText: '例如：192.168.1.100',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.dns),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入 IP 地址';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 端口
              TextFormField(
                controller: _portController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '端口',
                  hintText: '默认：22',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.dialpad),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入端口';
                  }
                  final port = int.tryParse(value);
                  if (port == null || port < 1 || port > 65535) {
                    return '端口范围：1-65535';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 用户名
              TextFormField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  hintText: '默认：root',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.person),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 密码
              TextFormField(
                controller: _passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  labelText: '密码',
                  hintText: isEditMode ? '留空则不修改密码' : '请输入密码',
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.lock),
                ),
                validator: (value) {
                  // 编辑模式下密码可以为空（表示不修改）
                  if (!isEditMode && (value == null || value.isEmpty)) {
                    return '请输入密码';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),

              // 提交按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _handleSubmit,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    isEditMode ? '保存修改' : '添加服务器',
                    style: const TextStyle(fontSize: 16),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _handleSubmit() {
    if (_formKey.currentState!.validate()) {
      widget.onSubmit(
        name: _nameController.text,
        host: _hostController.text,
        port: int.parse(_portController.text),
        username: _usernameController.text,
        password: _passwordController.text.isEmpty ? null : _passwordController.text,
        groupId: _selectedGroupId,
      );
    }
  }
}

